package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.vo.CourseCategoryTreeVo;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Override
    public List<CourseCategoryTreeVo> getTree() {

        List<CourseCategory> courseCategoryList = list();
        List<CourseCategoryTreeVo> courseCategoryTreeVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(courseCategoryList)){

            courseCategoryList.forEach(courseCategory -> {
                CourseCategoryTreeVo courseCategoryTreeVo = new CourseCategoryTreeVo();
                BeanUtils.copyProperties(courseCategory,courseCategoryTreeVo);

                courseCategoryTreeVoList.add(courseCategoryTreeVo);

            });
        }

        return getChildren("1",courseCategoryTreeVoList);
    }

    /**
     * 递归查询子节点
     * @param rootId  根节点id
     * @param all   所有节点
     * @return 根节点信息
     */
    private List<CourseCategoryTreeVo> getChildren(String rootId, List<CourseCategoryTreeVo> all) {
        List<CourseCategoryTreeVo> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentid(), rootId);
        }).map(
                (m) -> {
                    //当该节点有子节点时，才设置其属性,这一步做不做都无所谓，前端其实可以处理
                    List<CourseCategoryTreeVo> children1 = getChildren(m.getId(), all);
                    if (!CollectionUtils.isEmpty(children1)){
                        m.setChildrenTreeNodes(children1);
                    }
                    return m;
                }
        ).collect(Collectors.toList());
        return children; //返回的这个集合就是最终我们想要的树形结构集合了
    }
}
